const https = require('https');
const http = require('http');
const qs = require('querystring');
// require('chromedriver');
require('geckodriver');
const { Builder, By, Key, until, Browser } = require('selenium-webdriver');
// const chrome = require('selenium-webdriver/chrome');
const firefox  = require('selenium-webdriver/firefox');
const { pushLog, clearLog } = require('./middleware/log');
const adConfig = require('./config/adConfig');
const userDict = require("./config/user");
// const browser = new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless().windowSize({ height: 1000, width: 1080 }));
// var browser = new Builder().forBrowser('firefox').setFirefoxOptions(new firefox.Options().headless().windowSize({ height: 1000, width: 1080 }));
var browser = new Builder().forBrowser('firefox');
var driver = null;
try {
    var report = {
        url: process.env.NODE_ENV&&process.env.NODE_ENV.split("--")[1].split(":")[1].replace("//", ""),
        port: process.env.NODE_ENV&&process.env.NODE_ENV.split("--")[1].split(":")[2]
    }
    console.log(report);

} catch (error) {
    console.log("错误信息"+error)
}
pushLog('<b style="color:red">' + JSON.stringify(report) + "</b>")
var appList = null;//应用列表
var runingStatus = false; //脚本执行状态
var adList = null; // 待创建的广告位列表
var pageData = {
    pageIndex: 0,
    pageSize: 0,
}
var taskDtaList = [];
//账号列表
var userLogin = [];
//当前登录账号信息
var loginInfo = null;
//打开浏览器
async function open(list) {
    if (runingStatus) {
        pushLog("当前脚本正在执行中请耐心等待任务结束");
        return
    }
    runingStatus = true;
    clearLog();
    adList = list;
    userLogin = createUsers();
    // userLogin = userDict;
    if (userLogin.length == 0) {
        return
    }
    loginInfo = {
        status: 0,
        index: 0,
        userInfo: userLogin[0]
    }
    if(driver){
       driver = null;
    }
    driver = browser.build();
    driver.get("https://e.qq.com/dev/index.html").then(() => {
        pushLog("页面加载完成");
        auth();
    });
}
//构造任务数据
/**
 * parmars {Arr}
 */
function createTaskData() {
    try {
        let userInfo = loginInfo.userInfo;
        let taskD = adList['accounts'][userInfo.qq];
        let taskList = [];
        let tempData=null;
        taskD.forEach(item => {
            try {
                tempData = JSON.parse(JSON.stringify(adConfig[item.adType]));
            } catch (error) {
                tempData = null
            }
            if (tempData) {
                appList.forEach(appitem => {
                    if (appitem.outerMediumId == item.appCode) {
                        tempData['newPlacementAddVo'].mediumId = appitem.mediumId;
                        tempData['newPlacementAddVo'].memberId = userInfo.memberId;
                        tempData['newPlacementAddVo'].placementName = item.slotName;
                        tempData['newPlacementAddVo'].osType=item.osType==1?'Android':item.osType==2?"iOS":"Android";
                        taskList.push(tempData);
                    }
                })

            } else {
                try {
                    pushLog("未找到该类型的广告--adType："+item.adType+"")
                } catch (error) {
                    pushLog(JSON.stringify(error));
                }
              
            }
        })
        pushLog(loginInfo.userInfo.qq + "：任务创建成功...");
        return taskList;
    } catch (error) {
        pushLog("构造模板数据异常" + error.toString());
        return [];
    }
}
//创建任务账号

function createUsers() {
    try {
        let users = [];
        let noUser = [];
        userDict.forEach(item => {
            if (JSON.stringify(adList) != "{}") {
                // console.log(item.qq);
                // console.log(JSON.stringify(adList['accounts'][item.qq]));
                if (typeof adList['accounts'][item.qq] == "object") {
                    users.push(item);
                } else {
                    noUser.push(item);
                }
            }

        })


        // if(Object.prototype.toString.call(users)!=="[object Array]"&&)
        if (users.length == 0) {
            pushLog("无可用账号");
            // driver.get("https://adnet.qq.com/user/logout");
            driver.quit();

        } else {
            if (noUser.length > 0) {
                console.log(noUser)
                pushLog("未参与任务的账号：" + JSON.stringify(noUser));
            }
            console.log(users)
            pushLog("参与的任务账号：" + JSON.stringify(users));
        }
        return users;

    } catch (error) {
        pushLog("创建任务账号失败：" + JSON.stringify(error));
        // driver.get("https://adnet.qq.com/user/logout");
        driver.quit();
    }

}
//去授权页面
async function auth() {
    let flag = true;
    driver.findElement(By.id('loginBtn')).click();
    if (flag) {
        pushLog("进入授权页面");
        await driver.sleep(4000).then(() => {
            iframe = driver.findElement(By.id("ptlogin_iframe"));
            driver.switchTo().frame(iframe).then(() => {
                login();
            });
        });
    }
}

//获取填充的cookies
function getCookie() {
    console.log('正在获取cookies');
    pushLog("正在获取cookies");
    return driver.manage().getCookies();
}
async function sycnData(cookie) {
    let cookies = cookie;
    console.log("同步数据的cookie" + cookies);
    console.log("同步数据的menberId" + loginInfo.userInfo.memberId);
    let reportAdList = {};
    //获取广告位列表
    pushLog("正在获取" + loginInfo.userInfo.qq + "创建的广告位");
    await formAjax(https,
        {
            searchCriteria: "",
            pageIndex: 0,
            pageSize: pageData.pageSize,
            memberId: loginInfo.userInfo.memberId
        },
        cookies,
        {
            hostname: 'adnet.qq.com',
            port: 443,
            path: '/placement/search',
            method: 'POST',
        },
        {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36",
            "Referer": "https://adnet.qq.com/placement/0/add",
            "Origin": "https://adnet.qq.com",
            "Host": "adnet.qq.com",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "cookie": cookies
        }
    ).then(res => {
        pageData = {
            pageIndex: 0,
            pageSize: 0,
        }
        if (res.ret == 0) {
            pushLog(loginInfo.userInfo.qq + "：广告位列表获取成功");
            reportAdList = res;
        } else {
            reportAdList = {};
            pushLog(loginInfo.userInfo.qq + "：广告位列表获取失败");
        }
        console.log("广告位列表" + JSON.stringify(res));
    }).catch(err => {
        pageData = {
            pageIndex: 0,
            pageSize: 0,
        }
        console.log("获取广告位列表失败" + JSON.stringify(err));
    })

    if (JSON.stringify(reportAdList) !== "{}") {
        //同步广告位数据
        await formAjax(http,
            {
                header: { token: adList.token },
                body: reportAdList,
                string: true
            }
            , "",
            {
                hostname: report.url,
                port: report.port,
                path: '/source/app/slot/private/import/autoconfig.do',
                method: 'POST',
            },
            {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36",
                // "Origin":"http//"+report.url+":"+report.port,
                // "Host": "http//"+report.url+":"+report.port,
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "cookie": ""
            }).then((res) => {
                if (res.code == 0) {
                    pushLog(loginInfo.userInfo.qq + "：数据同步成功")
                } else {
                    pushLog(loginInfo.userInfo.qq + "：数据同步失败" + JSON.stringify(res));
                }
                // console.log(res)
            }).catch((err) => {
                pushLog("<b style='color:red'>" + loginInfo.userInfo.qq + "：数据同步失败" + JSON.stringify(err) + "</b>");
            });


    } else {
        pushLog(loginInfo.userInfo.qq + "：数据未同步")
    }
}
//退出登录
async function loginOut(cookie) {
    if (loginInfo.index <= (userLogin.length - 1)) {
        //一个以上账号的情况
        //同步数据
        await sycnData(cookie);
        await driver.get("https://adnet.qq.com/user/logout");
        pushLog(loginInfo.userInfo.qq + "：退出登录");
        let newloginInfo = {
            status: 0,
            index: loginInfo.index + 1,
            userInfo: userLogin[loginInfo.index + 1]
        }
        loginInfo = newloginInfo;
        if (loginInfo.index <= (userLogin.length - 1)) {
            console.log('\x1B[33m%s\x1b[0m:', "继续下一个任务");
            auth();
        } else {
            loginInfo = {
                status: 0,
                index: 0,
                userInfo: userLogin[0]
            }
            await driver.get("https://adnet.qq.com/user/logout");
            driver.quit();
            runingStatus = false;
            console.log('\x1B[33m%s\x1b[0m:', "所有任务结束");
            pushLog("<b style='color:red'>任务结束...</b>");
        }
    }
}
//授权登录
function login() {
    let cookie = "";
    (async function isPageload() {
        let authQQ = await driver.findElement(By.id("qlogin_list")).findElement(By.xpath("//a[@uin=" + loginInfo.userInfo.qq + "]")).then(el => {
            driver.executeScript("arguments[0].click()", el).then(() => {
                driver.switchTo().defaultContent();
            });
            return true;
        }).catch(async () => {
            //未找到账号的处理方式
            if (loginInfo.index <= userLogin.length - 1) {
                if (loginInfo.index == userLogin.length - 1) {
                    runingStatus = false;
                    pushLog(loginInfo.userInfo.qq + "账号不可用：任务结束");
                    loginInfo = {
                        status: 0,
                        index: 0,
                        userInfo: userLogin[0]
                    }
                    await driver.get("https://adnet.qq.com/user/logout");
                    driver.quit();
                } else {
                    pushLog(loginInfo.userInfo.qq + "账号不可用正在切换下一个");
                    loginInfo = {
                        status: 0,
                        index: loginInfo.index + 1,
                        userInfo: userLogin[loginInfo.index + 1]
                    }
                    isPageload();
                }
            }
            return false;
        });
        if (!authQQ) return;
        console.log("账号登录成功" + loginInfo.userInfo.qq);
        let as = await driver.wait(until.elementLocated(By.id('messageCenter')), 1000 * 60).catch(() => { console.log("登录失败") });
        if (!as) return;
        console.log(loginInfo.userInfo.qq + "登录成功", as.getId());
        pushLog(loginInfo.userInfo.qq + "：登录成功");
        await getCookie().then(res => {
            res.forEach((item, index) => {
                if (index == res.length - 1) {
                    cookie += (item.name + "=" + item.value);
                } else {
                    cookie += (item.name + "=" + item.value + "; ")
                }
            })
        });
        //获取应用列表
        await ajax(https, "", cookie, {
            hostname: 'adnet.qq.com',
            port: 443,
            path: '/medium/list/' + loginInfo.userInfo.memberId,
            method: 'GET',
        }).then(res => {
            pushLog("应用列表请求完成：" + res.message);
            if (res.ret == 0) {
                appList = res.data;
                // console.log(typeof appList,"应用列表")
            }
        }).catch(err => {
            pushLog("获取应用列表失败:" + JSON.stringify(err));

        });
        //生成任务列表 
        taskDtaList = createTaskData();
        //创建代码
        async function create() {
            await driver.sleep(1000).then(() => {
                console.log("任务信息" + JSON.stringify(taskDtaList))
                let task = taskDtaList.pop();
                console.log("当前创建的广告位信息" + JSON.stringify(task));
                if (typeof task !== "undefined") {
                    pushLog("创建广告位中....");
                    ajax(https, task, cookie).then((res) => {
                        if (res.ret == 0) {
                            pageData.pageSize = pageData.pageSize + 1
                            pushLog("操作完成：" + res.message + "[" + (res.data.length > 0 ? res.data[0] : '') + "]");
                        } else {
                            pushLog("操作完成：未完成创建-" + res.message);
                        }
                        console.log(res);
                        create();
                    }).catch((err) => {
                        //退出装好
                        console.log(err)
                        pushLog("创建广告位失败:" + JSON.stringify(err.message));
                        create();
                    })
                } else {
                    loginOut(cookie);
                    return false
                }
            });
        }
        await create();
    })();
}

function ajax(protocol, data, cookie, params) {
    let option = params || {
        hostname: 'adnet.qq.com',
        // hostname:'127.0.0.1',
        port: 443,
        path: '/placement/create',
        method: 'POST',
        // protocol: "https" //默认使用https
    }
    return new Promise((resolve, reject) => {
        var post_data = { ...data };
        var content = JSON.stringify(post_data);
        var options = {
            ...option,
            headers: {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36",
                "Referer": "https://adnet.qq.com/placement/0/add",
                "Origin": "https://adnet.qq.com",
                "Host": "adnet.qq.com",
                "Content-Type": "application/json",
                "cookie": cookie
            }
        };

        var req = protocol.request(options, function (res) {
            console.log('STATUS(响应状态): ' + res.statusCode);
            console.log('HEADERS(响应头): ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            let resData = ""
            res.on('data', function (chunk) {
                // console.log('BODY(响应体): ' + chunk);
                resData += chunk;
                // resolve(chunk);
            });
            res.on('end', function () {
                // console.log(resData,"响应数据");
                console.log(JSON.stringify(resData));
                try {
                    resolve(JSON.parse(resData));
                } catch (error) {
                    resolve({ ret: -100, message: "*******", data: [] });
                }

            });
        });
        req.on('error', function (e) {
            console.log('problem with request(请求失败): ' + e.message);
            reject(e);
        });
        // 将数据写入请求体
        req.write(content);//注意这个地方  
        req.end();
    })
}

function formAjax(protocol, data, cookie, params, headers) {
    let option = params || {
        hostname: 'adnet.qq.com',
        path: '/placement/create',
        method: 'POST',
    }
    return new Promise((resolve, reject) => {
        var post_data = { ...data };
        var content = post_data.string ? JSON.stringify(post_data) : qs.stringify(post_data);
        var options = {
            ...option,
            headers: headers || {
                "cookie": cookie
            }
        };

        var req = protocol.request(options, function (res) {
            // console.log('STATUS(响应状态): ' + res.statusCode);
            // console.log('HEADERS(响应头): ' + JSON.stringify(res.headers));
            res.setEncoding('utf8');
            let resData = ""
            res.on('data', function (chunk) {
                // console.log('BODY(响应体): ' + chunk);
                resData += chunk;
                // resolve(chunk);
            });
            res.on('end', function () {
                // console.log(resData, "响应数据");
                console.log("返回的数据：" + resData);
                try {
                    resolve(JSON.parse(resData));
                } catch (error) {

                    resolve({ ret: -100, message: "*******", data: [] });
                }

            });
        });
        req.on('error', function (e) {
            console.log('problem with request(请求失败): ' + e.message);

            reject(e);
        });
        console.log("发送的数据体：", content);
        // 将数据写入请求体
        req.write(content);//注意这个地方  
        req.end();
    })
}

function getRunStatus() {
    return runingStatus;
}
// process.on('uncaughtException', (err) => {
//     console.log("系统异常:" + err);
//     pushLog("系统异常：" + JSON.stringify(err))
//     runingStatus=true;
// });
module.exports = { open, getRunStatus };
